import React, { useEffect } from "react";
import { Form, Input, Button, message } from "antd";
import { useLocation } from "react-router-dom";
import { loginDataType } from "../../interface";
import { apiLogin, apiGiteeLogin } from "../../api";
import Cookie from "js-cookie";
import "./style.css";

const Login = () => {

  const onFinish = (data: loginDataType) => {
    apiLogin(data).then((res: any) => {
      //保存到本地
      Cookie.set("token", res.token);
      window.location.href = "/home";
    });
  };

  const location = useLocation();

  useEffect(() => {
    // 判断code是否存在
    if (location.search) {
      // 将code提取出来
      const code = location.search.split("?code=");
      if (!code[0]) {
        // 发送第三方登录请求
        apiGiteeLogin({ code: code[1] }).then((res: any) => {
          // 将token 保存到本地
          Cookie.set("token", res.token);
          // 提示用户登录成功
          message.success("登录成功,即将跳转首页");
          // 跳转页面
          window.location.href = "/home";
        });
      }
    }
  }, [location]);

  const toGiteeLogin = () => {
    window.location.href =
      "https://gitee.com/oauth/authorize?client_id=9af66fcadad19c10be73154261e8da50bd8ad2894d189b9973daf84b6d235058&redirect_uri=http://127.0.0.1:3000/login&response_type=code";
  };

  return (
    <div className="container">
      <div className="box">
        <div className="aa">
          <h2>欢迎！</h2>

          <h3>欢迎宏烨找房管理后台</h3>

          <Button className="zhuce">
            <a href="../Register">注册</a>
          </Button>
        </div>

        <div className="login">
          <div className="a">
            <h2>登录</h2>
            <Form name="basic" onFinish={onFinish} autoComplete="off">
              <Form.Item
                label="账户"
                name="username"
                rules={[{ required: true, message: "请输入账户" }]}
              >
                <Input />
              </Form.Item>

              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password />
              </Form.Item>

              <Form.Item>
                <Button type="primary" htmlType="submit">
                  登录
                </Button>
              </Form.Item>

              <Form.Item>
                <Button type="primary" danger onClick={toGiteeLogin}>
                  第三方登录
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Login;
